<template>
  <div id="app">
    <div class="container">
      <div class="navbar">
        <h2>{{game?.name || '加载中...'}}</h2>
      </div>
      
      <!-- Tab 切换 -->
      <div class="tabs">
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'backend' }"
          @click="activeTab = 'backend'"
        >
          物品后台
        </div>
        <template v-if="base && base.links">
          <div 
            v-for="link in base.links" 
            :key="link.id"
            class="tab-item" 
            :class="{ active: activeTab === 'link-' + link.id }"
            @click="activeTab = 'link-' + link.id"
          >
            {{link.intro}}
          </div>
        </template>
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'cdk' }"
          @click="activeTab = 'cdk'"
        >
          激活后台
        </div>
      </div>

      <!-- 物品后台内容 -->
      <div v-if="activeTab === 'backend'">
        <form @submit.prevent="submitForm" v-if="game">
          <div class="form-group">
            <label for="uid">{{game.uidTip}}</label>
            <input type="text" id="uid" v-model="formData.uid" :placeholder="'请输入' + game.uidTip">
          </div>

          <div class="form-group" v-if="base?.qufu?.length > 0">
            <label for="qufu">大区</label>
            <select id="qufu" v-model="formData.qufu">
              <option value="">请选择...</option>
              <option v-for="item in base.qufu" :key="item.id" :value="item.value">{{ item.name }}</option>
            </select>
          </div>

          <div class="form-group" v-if="base?.gongneng?.length > 0">
            <label for="gongneng">功能</label>
            <select id="gongneng" v-model="formData.gongnengId" @change="handleGongnengChange">
              <option value="">请选择...</option>
              <option v-for="item in base.gongneng" :key="item.gid" :value="item.gid">{{ item.name }}</option>
            </select>
          </div>

          <div class="form-group" v-if="items.length > 0">
            <label for="itemId">道具</label>
            <div class="search-input-wrapper">
              <input type="text" v-model="searchQuery" placeholder="道具搜索..." v-if="items.length > 10">
              <span v-if="searchQuery" class="clear-icon" @click="searchQuery = ''"></span>
            </div>
            <select id="itemId" v-model="formData.itemId">
              <option value="">请选择...</option>
              <option v-for="item in filteredItems" :key="item.c" :value="item.c">{{ item.n }}</option>
            </select>
          </div>

          <div class="form-group" v-if="numVisable">
            <label for="number">数量</label>
            <input type="number" id="number" min="1" placeholder="请输入数量" v-model="formData.number">
          </div>

          <div class="form-group">
            <button type="button" :disabled="loading" @click="submitForm">{{ loading ? '发送中...' : '发送' }}</button>
          </div>
        </form>
      </div>

      <!-- Links 内容 -->
      <template v-if="base && base.links">
        <div v-for="link in base.links" :key="link.id" class="iframe-container" v-show="activeTab === 'link-' + link.id">
          <iframe v-if="activeTab === 'link-' + link.id" :src="link.url" frameborder="0"></iframe>
        </div>
      </template>

      <!-- CDK 内容 -->
      <div v-if="activeTab === 'cdk'">
        <form @submit.prevent="submitCdkForm" v-if="game">
          <div class="form-group">
            <label for="cdk-uid">{{game.uidTip}}</label>
            <input type="text" id="cdk-uid" v-model="cdkFormData.uid" :placeholder="'请输入' + game.uidTip">
          </div>

          <div class="form-group">
            <label for="cdk">CDK</label>
            <input type="text" id="cdk" placeholder="请输入CDK" v-model="cdkFormData.cdk">
          </div>

          <div class="form-group">
            <button type="submit" :disabled="cdkLoading">{{ cdkLoading ? '激活中...' : '激活' }}</button>
          </div>
        </form>
      </div>

    </div>

    <!-- 提示框 -->
    <div class="alert-box" v-if="game?.backendTips && activeTab === 'backend'">
      <span v-html="game.backendTips"></span>
    </div>
    <div class="alert-box" v-if="game?.cdkTips && activeTab === 'cdk'">
      <span v-html="game.cdkTips"></span>
    </div>

    <!-- Toast 提示 -->
    <div class="toast" :class="{ show: showToast }">
      {{ toastMessage }}
    </div>

    <!-- 错误弹窗 -->
    <div class="modal" v-if="showModal">
      <div class="modal-content">
        <h3>提示</h3>
        <p>{{ modalMessage }}</p>
        <button @click="closeModal">确定</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BackendPage'
}
</script>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import {useRoute} from 'vue-router'

const route = useRoute()
const gameId = ref(null)
const lastRequestTime = ref(0)
const interval = 1000 // 设置请求间隔为 1 秒
const cdkInterval = 3000 // CDK 请求间隔为 3 秒

const game = ref(null)
const base = ref({
  qufu: [],
  gongneng: [],
  links: []
})
const items = ref([])
const formData = ref({
  gameId: '',
  uid: '',
  qufu: '',
  gongnengId: '',
  itemId: '',
  number: null
})
const cdkFormData = ref({
  gameId: '',
  uid: '',
  cdk: ''
})
const searchQuery = ref('')
const numVisable = ref(true)
const activeTab = ref('backend') // 默认显示后台页面

// 添加新的响应式变量
const showToast = ref(false)
const toastMessage = ref('')
const showModal = ref(false)
const modalMessage = ref('')
const loading = ref(false)
const cdkLoading = ref(false)


const getGameIdFromUrl = () => {
  gameId.value = route.query.gameId
  if (gameId.value) {
    const savedGames = JSON.parse(localStorage.getItem('savedGames') || '[]')
    const savedGame = savedGames.find(g => String(g.gameId) === String(gameId.value))
    if (savedGame) {
      formData.value.uid = savedGame.uid
      cdkFormData.value.uid = savedGame.uid
    }
  }
}

const getDetail = async () => {
  try {
    const response = await fetch("/api/backend/base", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"
      },
      body: JSON.stringify({ gameId: gameId.value })
    })
    const data = await response.json()
    if (data) {
      base.value = {
        ...data,
        qufu: data.qufu || [],
        gongneng: data.gongneng || [],
        links: data.links || []
      }
      game.value = base.value.game
    }
  } catch (error) {
    console.error('获取游戏数据失败:', error)
    errorTip('获取游戏数据失败！')
  }
}

const handleGongnengChange = () => {
  const gongneng = base.value.gongneng.find(item => item.gid === formData.value.gongnengId)
  if (gongneng) {
    numVisable.value = gongneng.num
    if (gongneng.req) {
      requestItems(gongneng.gid)
    } else {
      items.value = []
    }
  }
  searchQuery.value = ''
  formData.value.itemId = ''
}

const requestItems = async (gongnengId) => {
  try {
    const response = await fetch("/api/backend/items", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"
      },
      body: JSON.stringify({
        gameId: gameId.value,
        gongnengId: gongnengId
      })
    })
    const data = await response.json()
    items.value = data
  } catch (error) {
    console.error('获取道具数据失败:', error)
    errorTip('获取道具数据失败！')
  }
}

const checkForm = () => {
  if (!formData.value.uid.trim()) {
    errorTip('请输入' + game.value.uidTip)
    return false
  }

  if (base.value.qufu.length > 0 && !formData.value.qufu) {
    errorTip('请选择大区')
    return false
  }

  if (!formData.value.gongnengId) {
    errorTip('请选择功能')
    return false
  }

  if (items.value.length > 0 && !formData.value.itemId) {
    errorTip('请选择道具')
    return false
  }

  if (numVisable.value && !formData.value.number) {
    errorTip('请输入数量')
    return false
  }

  const currentTime = new Date().getTime()
  if (currentTime - lastRequestTime.value < interval) {
    errorTip('点太快了~')
    return false
  }
  lastRequestTime.value = currentTime
  return true
}

const checkCdkForm = () => {
  if (!cdkFormData.value.uid.trim()) {
    errorTip('请输入' + game.value.uidTip)
    return false
  }

  if (!cdkFormData.value.cdk) {
    errorTip('请输入CDK')
    return false
  }

  const currentTime = new Date().getTime()
  if (currentTime - lastRequestTime.value < cdkInterval) {
    errorTip('点太快了~')
    return false
  }
  lastRequestTime.value = currentTime
  return true
}

const saveGameUid = () => {
  const savedGames = JSON.parse(localStorage.getItem('savedGames') || '[]')
  const gameInfo = {
    gameId: game.value.id,
    gameName: game.value.name,
    uid: formData.value.uid
  }
  
  const existingIndex = savedGames.findIndex(g => g.gameId === game.value.id)
  if (existingIndex !== -1) {
    savedGames[existingIndex] = gameInfo
  } else {
    savedGames.push(gameInfo)
  }
  
  localStorage.setItem('savedGames', JSON.stringify(savedGames))
}

const submitForm = async () => {
  if (!checkForm()) return
  formData.value.gameId = gameId.value
  
  loading.value = true
  try {
    const response = await fetch("/api/backend/send", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"
      },
      body: JSON.stringify(formData.value)
    })
    const data = await response.text()
    if (!response.ok) {
      errorTip(data)
    } else {
      saveGameUid()
      successTip(data)
    }
  } catch (error) {
    console.error('发送失败:', error)
    errorTip('发送失败，请重试')
  } finally {
    loading.value = false
  }
}

const submitCdkForm = async () => {
  if (!checkCdkForm()) return
  cdkFormData.value.gameId = gameId.value
  
  cdkLoading.value = true
  try {
    const response = await fetch('/api/cdk/use', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(cdkFormData.value)
    })
    const data = await response.text()
    if (data.includes('成功')) {
      // 激活成功后保存 uid
      const savedGames = JSON.parse(localStorage.getItem('savedGames') || '[]')
      const gameInfo = {
        gameId: game.value.id,
        gameName: game.value.name,
        uid: cdkFormData.value.uid
      }
      
      const existingIndex = savedGames.findIndex(g => g.gameId === game.value.id)
      if (existingIndex !== -1) {
        savedGames[existingIndex] = gameInfo
      } else {
        savedGames.push(gameInfo)
      }
      
      localStorage.setItem('savedGames', JSON.stringify(savedGames))
      
      // 同步更新后台表单的 uid
      formData.value.uid = cdkFormData.value.uid
      
      successTip(data)
      activeTab.value = 'backend'
    } else {
      errorTip(data)
    }
  } catch (error) {
    console.error('激活失败:', error)
    errorTip('激活失败，请重试')
  } finally {
    cdkLoading.value = false
  }
}

const errorTip = (msg) => {
  modalMessage.value = msg
  showModal.value = true
}

const successTip = (msg) => {
  toastMessage.value = msg
  showToast.value = true
  setTimeout(() => {
    showToast.value = false
  }, 2000)
}

const closeModal = () => {
  showModal.value = false
}

const filteredItems = computed(() => {
  const filtered = items.value.filter(item =>
    item.n.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
  return filtered
})

watch([searchQuery, filteredItems], ([newVal, filtered]) => {
  if (newVal && filtered.length === 0) {
    successTip('未找到匹配的道具')
  }
})

// 监听路由参数变化
watch(() => route.query.gameId, (newGameId) => {
  if (newGameId && newGameId !== gameId.value) {
    gameId.value = newGameId
    getGameIdFromUrl()
    getDetail()
  }
}, { immediate: true })

onMounted(() => {
  getGameIdFromUrl()
  if (gameId.value) {
    getDetail()
  }
})
</script>

<style scoped>
body {
  font-family: Arial, sans-serif;
  background-color: #f5f5f5;
  color: #333;
  margin: 0;
  padding: 20px;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  background: #fff;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.navbar h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #ddd;
}

.tab-item {
  padding: 10px 20px;
  cursor: pointer;
  font-size: 16px;
  color: #666;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
}

.tab-item:hover {
  color: #409EFF;
}

.tab-item.active {
  color: #409EFF;
  border-bottom-color: #409EFF;
}

@media (max-width: 600px) {
  .tab-item {
    padding: 8px 15px;
    font-size: 14px;
  }
}

.form-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
}

.form-group label {
  margin-bottom: 5px;
  color: #333;
  font-weight: 500;
}

.form-group select,
.form-group input {
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
  width: 100%;
  color: #333;
  background-color: #fff;
}

/* 移除select默认样式 */
select {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 10px center;
  background-size: 16px;
  padding-right: 40px;
}

.form-group button {
  padding: 10px 20px;
  background-color: #5cb85c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.form-group button:hover {
  background-color: #4cae4c;
}

/* 提示框样式 */
.alert-box {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background-color: #f2dede;
  border: 2px solid #dca7a7;
  color: #a94442;
  font-size: 18px;
  border-radius: 8px;
}

.alert-box p {
  margin: 0;
}

@media (max-width: 600px) {
  body {
    padding: 10px;
  }
  
  .container {
    padding: 15px;
  }
  
  .navbar h2 {
    font-size: 20px;
  }
  
  .form-group select,
  .form-group input {
    font-size: 16px;
    padding: 8px;
  }
  
  .form-group button {
    padding: 8px 16px;
    font-size: 16px;
  }
  
  .alert-box {
    font-size: 16px;
    padding: 15px;
  }
}

.loading {
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 16px;
}

/* Toast 样式 */
.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 12px 24px;
  border-radius: 4px;
  font-size: 14px;
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
  z-index: 1000;
  min-width: 200px;
  text-align: center;
}

.toast.show {
  opacity: 1;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 80%;
  max-width: 400px;
  text-align: center;
}

.modal-content h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.modal-content p {
  margin: 0 0 20px 0;
  color: #666;
}

.modal-content button {
  padding: 8px 20px;
  background-color: #5cb85c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.modal-content button:hover {
  background-color: #4cae4c;
}

@media (max-width: 600px) {
  .modal-content {
    width: 90%;
    padding: 15px;
  }
  
  .toast {
    width: 80%;
    min-width: auto;
  }
}

.search-input-wrapper {
  position: relative;
  width: 100%;
}

.search-input-wrapper input {
  padding-right: 30px;
}

.clear-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  color: #999;
  cursor: pointer;
  font-size: 18px;
  user-select: none;
}

.clear-icon:hover {
  color: #666;
}

@media (max-width: 600px) {
  .clear-icon {
    width: 24px;
    height: 24px;
    line-height: 24px;
    font-size: 20px;
  }
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
  opacity: 0.7;
}

.iframe-container {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  height: calc(100vh - 200px);
}

.iframe-container iframe {
  width: 100%;
  height: 100%;
  border: none;
}
</style> 